package com.lgl.scsheader.sameCityManage.service;

import com.lgl.scsapi.base.dao.DaoSupport;
import com.lgl.scsapi.system.model.PageData;
import com.lgl.scsapi.util.utils.Constants;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;

/**
 * 同城统计service
 */

@Service("sameCityCountService")
public class SameCityCountService {
	@Resource(name = "daoSupport")
	private DaoSupport dao;
	@Resource
	private RedisTemplate redisTemplate;

	/**
	 * 保存上个月有多少个用户登录
	 * @return 用户集合
	 */
	public int saveLoginOfAppUserNumLastMonth(){
		PageData countDataPd = new PageData(4);
		countDataPd.put("countType","0");
		Calendar calendar = Calendar.getInstance();
		int lastMonth = calendar.get(Calendar.MONTH), currentYear = calendar.get(Calendar.YEAR);
		//如果当前月份是1月份，则上个月就是12月，年份也相应减去1
		if (lastMonth < 1){
			lastMonth = 12;
			currentYear --;
		}
		calendar.set(Calendar.YEAR,currentYear);
		calendar.set(Calendar.MONTH,lastMonth);
		int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		byte[][] keyBytes = new byte[maxDay][];
		for (int m = 1; m <= maxDay; m ++){
			keyBytes[m - 1] = (Constants.USER_LOGIN_SET_PRE + lastMonth + m).getBytes();
		}
		String tempSaveKey = Constants.USER_LOGIN_SET_PRE + lastMonth;
		redisTemplate.execute((RedisCallback) con ->
			con.bitOp(RedisStringCommands.BitOperation.OR,tempSaveKey.getBytes(),keyBytes));
		long loginTimes = (Long) redisTemplate.execute((RedisCallback) con -> con.bitCount(tempSaveKey.getBytes()));
		redisTemplate.delete(tempSaveKey);
		countDataPd.put("data1",loginTimes);
		countDataPd.put("countDate",currentYear + "-" + lastMonth);
		return dao.save("SysCountDataMapper.saveLoginOfAppUserNum", countDataPd);
	}

}
